/**
* @file  letters
* @date 2024-02-22
*/

import { useEffect, useRef, useState } from "react";
import * as d3 from 'd3'
import { useInterval } from "../hooks";
import './Letters.css'

const Letters = () => {
  const ref = useRef(null)
  const randomLetters = () => d3.shuffle('abcdefghijklmnopqrstuvwxyz'.split("")).slice(0, Math.floor(6 + Math.random() * 20)).sort()
  const [letters, setLetters] = useState(() => randomLetters())
  useInterval(() => {
    setLetters(randomLetters())
  }, 2500)

  useEffect(() => {
    // 假设每个字母占据16个单位宽度
    const letterWidth = 24;
    // const letters = randomLetters()
    // 根据字母数量计算宽度
    const width = letters.length * letterWidth;
    const svgElement = d3.select(ref.current).attr('width', width).attr('height', 33).attr('viewBox', `0 -20 ${width} 33`)
    //随机动态展示字母
    // svgElement.selectAll('text').data(letters).join('text').attr("x", (d, i) => {
    //   console.log('d', d)
    //   return i * letterWidth
    // }).text(d => d)
    const t: any = svgElement.transition()
      .duration(750);
    //动态过渡颜色变化字母
    svgElement.selectAll('text').data(letters, d => d as any)
      .join(
        enter => enter.append("text")
          .attr("fill", "green")
          .attr("x", (d, i) => i * letterWidth)
          .attr("y", -30)
          .text(d => d)
          .call(enter => enter.transition(t)
            .attr("y", 0)),
        update => update
          .attr("fill", "black")
          .attr("y", 0)
          .call(update => update.transition(t)
            .attr("x", (d, i) => i * letterWidth)),
        exit => exit
          .attr("fill", "brown")
          .call(exit => exit.transition(t)
            .attr("y", 30)
            .remove()))
  }, [letters])


  return <svg
    ref={ref}
  />
};


export default Letters;
